import router from '@/main/router'

axios.defaults.timeout = 5000
const videoTimeout = 0 //视频上传取消超时限制

// 请求拦截
axios.interceptors.request.use(request => {
    //设置url(真实地址)
    if (!request.url.startsWith("http://") && !request.url.startsWith("https://")) {
        const urls = request.url.split('?')
        urls[0] = '/' + urls[0].split('/').filter(item => item !== '').join('/')
        if (urls[0] == '/uploads/image') {
            request.url = import.meta.env.VITE_INTERFACE_IMAGE
        } else if (urls[0] == '/uploads/video') {
            request.url = import.meta.env.VITE_INTERFACE_VIDEO
        } else {
            request.url = import.meta.env.VITE_INTERFACE + '/index.php?s=' + urls[0] + (urls[1] ? '&' + urls[1] : '')
        }
    }

    //视频上传取消超时
    if (request.url == import.meta.env.VITE_INTERFACE_VIDEO) {
        request.timeout = videoTimeout;
    }
    //其他设置
    if (request.method == 'get') {
        request.headers['Content-Type'] = 'application/json'
        //这个参数与后台有冲突所以去除掉
        if (request.params && request.params.s) {
            delete request.params.s;
        }
    } else if (request.method == 'post') {
        if (request.data instanceof FormData) {
            request.headers['Content-Type'] = 'multipart/form-data';
        } else {
            request.headers['Content-Type'] = 'application/x-www-form-urlencoded';
        }
    }
    //携带登陆信息
    const loginToken = localStorage.getItem(config.storage.loginToken) || ''
    if (loginToken.length == 32) {
        request.headers['Authorization'] = loginToken;
    }
    return request
}, error => {
    sys.tip({
        message: error.message,
        type: 'error',
        showClose: true,
        duration: 0
    })
    return Promise.reject(error)
})
// 返回拦截
axios.interceptors.response.use(async response => {
    //返回格式判断
    if (response.request.responseType == 'blob') {//blob数据
        if (response.data.type == 'text/html') {
            const string = new TextDecoder().decode(await response.data.arrayBuffer());
            try {
                response.data = JSON.parse(string)
            } catch (error) {
                response.data = string
            }
        } else {
            if (response.headers['content-disposition']) {
                response.data.disposition = response.headers['content-disposition']
            }
        }
    }
    //返回数据判断
    if (typeof response.data == 'string') {//如果服务器返回的不是object格式
        sys.tip({
            message: response.data,
            type: 'error',
            showClose: true,
            duration: 0
        })
        return { 'status': 0, 'message': response.data, 'data': {} }
    }
    if (response.data.status == 99) {//未登录
        router.push('/login?back=' + encodeURIComponent(router.currentRoute.value.fullPath))
    }
    if (response.data.status == 98) {//无权限
        sys.tip(response.data)
    }
    return response.data
}, function (error) {
    let message = error.message;
    switch (error.code) {
        case 'ECONNABORTED':
            message = '接口请求超过' + (axios.defaults.timeout / 1000) + '秒,已终止请求,请刷新页面重试'
            break;
        case 'ERR_NETWORK':
            message = '接口服务器访问出错,请刷新页面重试'
            break;
    }
    sys.tip({
        message: message,
        type: 'error',
        showClose: true,
        duration: 0
    })
    return Promise.reject(error)
});
